package it.webbased.site.client;


import java.io.Serializable;

@SuppressWarnings("serial")
public class ContactDataItem implements Serializable {
	
	public enum ItemType implements Serializable {
		EMAIL, BOX, AREA
	}
	
	private String value;
	private boolean required;
	private ItemType type;
	
	public ContactDataItem () {	
	}
	
	public ContactDataItem(boolean required, ItemType type) {
		this.required = required;
		this.type = type;
	}
	
	public void setValue(String value) {
		this.value = value;
	}
	
	public String getValue() {
		return value;
	}
	public ItemType getType() {
		return type;
	}
	public boolean isRequired() {
		return required;
	}
	
	public boolean validate(boolean entitize) {
		if((required) && value.isEmpty())
			return false;
		// Encode HTML entities
		if(entitize) {
			StringBuilder buf = new StringBuilder(value.length());
			for ( int i = 0; i < value.length(); i++ )
			{
				char c = value.charAt( i );
				String valid = new String(" òàùèé@._-");
				if ( c>='a' && c<='z' || c>='A' && c<='Z' || c>='0' && c<='9' || valid.indexOf(c) != -1 )
				{
					buf.append( c );
				}
				else
				{
					buf.append("&#").append((int)c).append(";");
				}
			}
			value = buf.toString();
		}
		switch (type) {
		case EMAIL:
			return value.matches("^.+@.+\\.[a-z]{2,4}$");
		case BOX:
			return !value.matches("\n");
		case AREA:
			return true;
		}
		return true;
	}

}